package process

import (
	"chatroom/common/message"
	"chatroom/server/utils"
	"encoding/json"
	"fmt"
	"net"
)

type UserProcess struct {
	Conn net.Conn
}

func (this *UserProcess) ServerProcessLogin(mes *message.Message) (err error) {
	loginReqData := mes.Data
	// 反序列化data
	var loginReqMessage message.LoginReqMessage
	err = json.Unmarshal([]byte(loginReqData), &loginReqMessage)
	if err != nil {
		fmt.Println("---json.Unmarshal---err", err)
	}

	// 逻辑处理
	var resMessage message.Message
	var loginResData message.LoginResMessage
	resMessage.MsgType = message.LoginResType
	if loginReqMessage.UserId == 100 && loginReqMessage.UserPwd == "123456" {
		loginResData.Code = 200
		loginResData.Msg = "登录成功"
		loginResData.Data = "token=abc123xxx"
	} else {
		loginResData.Code = 500
		loginResData.Msg = "登录失败"
		loginResData.Data = "token=null"
	}

	// 响应数据序列化
	// 序列化loginResData
	data, err := json.Marshal(loginResData)
	if err != nil {
		fmt.Println("---loginResData json.Marshal---err", err)
		return
	}
	resMessage.Data = string(data)

	// 序列化resMessage
	data, err = json.Marshal(resMessage)
	if err != nil {
		fmt.Println("---resMessage json.Marshal---err", err)
		return
	}

	// 发送data，我们将其封装到writePkg函数中
	tf := utils.Transfer{
		Conn: this.Conn,
	}
	err = tf.WritePkg(data)

	return
}
